package handler

import (
	"github.com/gin-gonic/gin"
	"logi-flow/cache"
	"logi-flow/moder"
	"logi-flow/pkj"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	reids_key := "error_login_" + username
	cacheData, _ := cache.Rdb.Get(cache.Ctx, reids_key).Int()
	if cacheData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次，禁止登录",
		})
		return
	}
	var user moder.User
	err := moder.DB.Where("username = ?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkj.Str(password) {
		cache.Rdb.Incr(cache.Ctx, reids_key)
		if cacheData == 2 {
			cache.Rdb.Set(cache.Ctx, reids_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次，封禁小二时",
			})
			return
		}

		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return

	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": user,
	})
	return
}
func RoleNodeList(c *gin.Context) {
	rid := c.Query("rid")
	/*
		SELECT
		  *
		FROM
		  `roles`
		  LEFT JOIN role_nodes ON roles.id = role_nodes.nid
		WHERE
		  role_nodes.rid = 1
	*/
	var Roles moder.Role
	moder.DB.Table("roles").
		Joins("LEFT JOIN role_nodes ON roles.id = role_nodes.rid").
		Where("role_nodes.rid = ?", rid).Find(&Roles)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": Roles,
	})
}
func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	/*
		SELECT
		  *
		FROM
		  users
		  LEFT JOIN user_roles ON users.id = user_roles.uid
		WHERE
		  user_roles.uid = 1
	*/
	var user moder.User
	moder.DB.Table("users").
		Joins(" LEFT JOIN user_roles ON users.id = user_roles.uid").
		Where(" user_roles.uid = ?", uid).Find(&user)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": user,
	})
}
func GetNidNodeList(c *gin.Context) {
	nid := c.Query("nid")
	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON nodes.id = role_nodes.nid
		WHERE
		  role_nodes.nid = 1
	*/
	var nodes moder.Node
	moder.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON nodes.id = role_nodes.nid").
		Where("role_nodes.nid = ?", nid).Find(&nodes)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": nodes,
	})
}
